# @Time : 2021-05-31 16:09 
# @Author : baldSun
# @File : emailSender.py 
# @Software: PyCharm

from stock_control.logDB import LogDB
from email.header import Header
from email.mime.text import MIMEText
from email.utils import parseaddr, formataddr

import smtplib


class EmailSender(object):
    def __init__(self):
        # 发件人地址
        self.from_addr = 'baldsun@163.com'
        # 邮箱SMTP服务授权码
        self.password = 'WOEZQMFULNBGNKBC'
        # 收件人地址
        self.to_addr = ['1045705525@qq.com', '932770426@qq.com']
        # 163网易邮箱服务器地址
        self.smtp_server = 'smtp.163.com'

    def _format_addr(self, s):
        name, addr = parseaddr(s)
        return formataddr((Header(name, 'utf-8').encode(), addr))

    # 设置交易邮件信息
    def set_transaction_msg(self, date, operation):
        # 查看数据库信息
        stocks = LogDB().get_by_date_and_operation(date, operation)
        if operation == 'sell':
            operation = '卖出'
        if operation == 'buy':
            operation = '买入'
        content = '尊敬的用户您好，自动交易系统今日为您'+operation+'如下股票：<br>'
        content = content + '<table style="text-align: center;">'
        content = content + '<tr>' + '<th>股票名</th><th>'+operation+'手数</th><th>'+operation+'价格(元/股)</th><th>资金变动</th></tr>'
        tol_money = 0
        # 当天有股票买入/卖出
        if len(stocks):
            for stock in stocks:
                money = stock['stock_num'] * 100 * stock['price']
                if operation == '买入':
                    money = money * (-1)
                tol_money = tol_money + money
                money = round(money, 2)
                content = content + '<tr>'
                content = content + '<td>' + stock['stock_name'] + '</td><td>' + str(stock['stock_num']) \
                          + '</td><td>' + str(stock['price']) + '</td><td>' + str(money) + '</td>'
                content = content + '</tr>'
            content = content + '</table>'
            content = content + '<br>今日' + operation + '资金变动：' + str(tol_money)
            content = content + '<div align="right">股票自动交易系统</div>'
            self.msg = MIMEText(content, 'html', 'utf-8')
            self.msg['From'] = self._format_addr('股票自动交易系统 <%s>' % self.from_addr)  # 邮件显示的发件人姓名
            self.msg['To'] = self._format_addr('用户 <%s>' % self.to_addr)
            self.msg['Subject'] = Header('股票' + operation + '提醒', 'utf-8').encode()
            return True
        else:
            # 当日无交易信息，返回错误
            return False

    # 设置系统开机/关机邮件信息
    def set_system_msg(self, date, operation):
        if operation == 'open':
            content = '&nbsp&nbsp&nbsp&nbsp尊敬的用户您好，股票自动交易系统已经开机，我们将从今日起为您选择最优策略自动买卖股票。' \
                      '感谢您的信任，我们将竭诚为您服务。'
            head = '股票自动交易系统开机提醒'
        else:
            content = '&nbsp&nbsp&nbsp&nbsp尊敬的用户您好，股票自动交易系统已经关机。' \
                      '感谢您的使用。'
            head = '股票自动交易系统关机提醒'
        self.msg = MIMEText(content, 'html', 'utf-8')
        self.msg['From'] = self._format_addr('股票自动交易系统 <%s>' % self.from_addr)  # 邮件显示的发件人姓名
        self.msg['To'] = self._format_addr('用户 <%s>' % self.to_addr)
        self.msg['Subject'] = Header(head, 'utf-8').encode()
        return True

    # 发送邮件
    def send_system_condition(self, date, operation):
        res = False
        if operation == 'open' or operation == 'close':
            res = self.set_system_msg(date, operation)
        else:
            res = self.set_transaction_msg(date, operation)
        # 当日无交易信息，返回错误
        if res == False:
            return res
        server = smtplib.SMTP(self.smtp_server, 25)
        server.login(self.from_addr, self.password)
        server.sendmail(self.from_addr, self.to_addr, self.msg.as_string())
        server.quit()
        return True

if __name__ == '__main__':
    es = EmailSender()
    # es.send_system_condition('2000-03-01', 'buy')
    # es.send_system_condition('2000-01-14', 'sell')
    es.send_system_condition('1992-04-13', 'open')
    es.send_system_condition('1992-04-13', 'buy')
    es.send_system_condition('1992-04-13', 'close')